<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>LAN-fileshare</title>
  <link rel="icon" href="fileshare/resources/images/favicon.ico" type="image/x-icon" />
  <link rel="stylesheet" href="fileshare/resources/css/bootstrap.min.css">
  <script src="fileshare/resources/js/jquery.min.js"></script>
  <script src="fileshare/resources/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="fileshare/resources/js/async.js"></script>
  <script type="text/javascript" src="fileshare/resources/js/sha1.js"></script>
  <script type="text/javascript" src="fileshare/resources/js/clipboard.min.js"></script>
  <style>
    .middleWidth {
      width: 65%;
    }

    .downlaod {
      width: 65%;
    }

    .top-20 {
      margin-top: 20px;
    }

    .notice {
      margin-top: 10px;
      color: grey;
    }

    .indent {
      border: 1px solid #ddd;
      height: 650px;
      margin-bottom: 20px;
      position: relative;
      width: 100%;
    }

    .padding-10 {
      margin-left: 10%;
    }

    .foot {
      margin: auto;
      text-align: center;
      width: 100%;
      color: #ccc;
      position: absolute;
      bottom: 20px;
    }

    .margin-120 {
      margin-top: 120px;
    }

    .bottom-20 {
      margin-bottom: 20px;
    }

    form {
      margin-top: 50px;
    }
  </style>
</head>

<body>

  <div class="row top-20">
    <div class="col-md-2"></div>
    <div class="col-md-8">
      <nav class="navbar navbar-default">
        <div class="container-fluid">
          <div class="navbar-header">
            <a class="navbar-brand" href="#">LAN-fileshare</a>
          </div>
        </div>
      </nav>

      <div class="indent">
        <div class="padding-10">
          <form action="upload.php">
            <div class="form-group">
              <label for="exampleInputFile">选择要上传的文件</label>
              <input type="file" id="file">
              <p class="help-block">文件最大不超过6G，上传后，即可分享文件的下载链接</p>
            </div>
          </form>

          <div class="middleWidth">
            <div class="progress">
              <div id="progress" class="progress-bar progress-bar-info progress-bar-striped active" role="progressbar" style="width: 0%;">

              </div>
            </div>
          </div>

          <div class="downlaod" hidden>
            <div class="input-group">
              <input id="downloadURL" type="text" class="form-control" placeholder="下载链接">
              <span class="input-group-btn">
                <button data-clipboard-target="#downloadURL" class="btn btn-default" type="button" id="copyBtn">拷贝</button>
              </span>
            </div>
            <div class="notice">
              <span>注意: 文件最多保存24小时，超过24小时，链接将会失效，文件将被自动删除</span>
            </div>
          </div>
        </div>

        <div class="padding-10 margin-120">
          <div class="bottom-20">
            <label for="">1. 连接校园网不登录账号可以使用吗?</label><br/>
            <span>可以，连接Ecust、Ecust-net无线网，有线网都可以</span>
          </div>
          <div class="bottom-20">
            <label for="">2. 我上传的文件会一直保留吗?</label><br/>
            <span>不会，文件上传后只保存24小时，请及时下载</span>
          </div>
          <div class="bottom-20">
            <label for="">3. 支持断点续传、断线续传吗?</label><br/>
            <span>不支持，以后会添加这个功能，且目前单次只能上传一个文件</span>
          </div>
        </div>

        <div class="foot">
          <i>Works of XiaoLee & lizhongcheng1004@163.com</i>
        </div>
      </div>

    </div>
    <div class="col-md-2"></div>
  </div>

  <script>
    new ClipboardJS('#copyBtn');
    var fileForm = document.getElementById("file");
    var stopBtn = document.getElementById('stop');

    const LENGTH = 5 * 1024 * 1024;
    const MAX_ALLOW_FILE_SIZE = 6 * 1024 * 1024 * 1024;
    var blob_num = 1;
    var total_blob_num = 0;
    var file_name = '';
    var file = null;
    const SEND_QUEUE_LENGTH = 5;
    var progressInit = 0;
    var received = 0;

    // 监听文件上传动作
    $('#file').on('change', function(evt) {
      progressInit = 0;
      received = 0;
      $('.downlaod').hide();
      $('#progress').css('width', '0%');
      $('#progress').text('');

      file = this.files[0];
      if (file.size > MAX_ALLOW_FILE_SIZE) {
        alert('上传文件过大(最大不超过6G)');
        return;
      }
      total_blob_num = Math.ceil(file.size / LENGTH);
      file_name = file.name;

      // disable文件上传按钮
      $('#file').attr('disabled', 'disabled');

      // 准备上传文件，请求服务器允许
      var form_data = new FormData();
      form_data.append('file_name', file.name);
      form_data.append('blob_size', LENGTH);
      form_data.append('file_size', file.size);
      form_data.append('total_blob_num', total_blob_num);
      $.ajax({
        processData: false,
        contentType: false,
        type: "POST",
        url: "prepare.php",
        data: form_data,
        dataType: "json",
        success: function(data) {
          console.log(data);
          if (data.code == 1) {
            $('#progress').text('0%');
            $('#progress').addClass('active');
            // 服务器允许上传，则开始上传文件
            addFileAndSend(file);
          } else {
            if (data.code == 0) {
              $('.downlaod').show();
              $('#downloadURL').val(data.downloadURL);
              $('#progress').css('width', '100%');
              $('#progress').text('文件已上传');
              $('#progress').removeClass('active');
            }
            // 服务器拒绝上传
            alert(data.msg);
          }
        }
      });
    });

    // 更新进度条
    function progress() {
      progressInit += 1;
      $('#progress').css('width', Math.min(100, Math.ceil((progressInit / total_blob_num) * 100)) + '%');
      $('#progress').text(Math.min(100, Math.ceil((progressInit / total_blob_num) * 100)) + '%');
    }

    //开始并行上传文件
    function addFileAndSend(file) {
      var slices = [];
      for (var i = 1; i <= total_blob_num; i++) {
        slices.push(i);
      }
      // 利用async库，并行上传文件分片
      async.mapLimit(slices, SEND_QUEUE_LENGTH, function(sliceNum, callback) {
        // process(sliceNum / total_blob_num);
        sendFile(cutFile(sliceNum), sliceNum, total_blob_num, file_name);
        callback(null);
      }, function(err, result) {
        if (err) {
          console.log('文件上传出错,请重试!');
        }
      });
    }

    //切割文件
    function cutFile(slice) {
      return file.slice(LENGTH * (slice - 1), LENGTH * slice);
    };

    // 请求服务器合并文件
    function requestJoinFile() {
      $('#progress').text('服务器正在准备文件，请稍后...');
      var form_data = new FormData();
      form_data.append('file_name', file_name);
      form_data.append('total_blob_num', total_blob_num);
      $.ajax({
        processData: false,
        contentType: false,
        type: "POST",
        url: "filejoin.php",
        data: form_data,
        dataType: "json",
        success: function(data) {
          if (!data.code) {
            alert('上传失败: ' + data.msg);
          } else {
            $('.downlaod').show();
            $('#downloadURL').val(data.downloadURL);
            $('#progress').text('上传完成');
            $('#progress').removeClass('active');
            alert('上传成功!');
            // enable上传文件按钮
            if ($('#file').attr("disabled") == 'disabled') {
              $('#file').removeAttr("disabled");
            }
          }
        }
      });
    }

    //发送文件
    function sendFile(blob, blob_num, total_blob_num, file_name) {
      // console.log('正在发送第 ' + blob_num + '个分片, size: ' + blob.size);

      var form_data = new FormData();
      form_data.append('file', blob);
      form_data.append('blob_num', blob_num);
      form_data.append('blob_size', blob.size);
      form_data.append('total_blob_num', total_blob_num);
      form_data.append('file_name', file_name);
      $.ajax({
        // async: false,
        processData: false,
        contentType: false,
        type: "POST",
        url: "upload.php",
        data: form_data,
        dataType: "json",
        success: function(data) {
          console.log(data);
          console.log("发送成功blob: " + blob_num);
          progress();
          received++;
          if (received == total_blob_num) {
            requestJoinFile();
          }
        }
      });
    }
  </script>
</body>

</html>